import React, { memo, useRef, useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { NavLink } from "react-router-dom";
import { SongListStyle } from "./style";
import { getSizeImage, getfg } from "@/utils/format-utils";
import { formalMinuteSeconds } from "@/utils/formatMinuteSecond";
import Four from "@/components/button/fourCheck";
import {
  getSongDetailsMessage,
  addSongId,
} from "../../../../pages/player/store/actionType";
import CoverMask from "@/components/coverMask";
import { getPlayUrl } from "@/utils/format-utils";

export default memo(function SongList(props) {
  const [btnNumber, setBtnNumber] = useState(null);
  const [open, setOpen] = useState(false);
  const trBoxRef = useRef();

  const dispatch = useDispatch();

  const getMusicLists = (ids) => {
    getPlayUrl(ids).then((res) => {
      // freeTrialInfo 若不为null则要收费
      if (res.data[0].freeTrialInfo) {
        setOpen(true);
        return;
      } else {
        setBtnNumber(ids);
        dispatch(getSongDetailsMessage(ids));
        dispatch(addSongId(ids));
      }
    });
  };

  const collectSongs = (id) => {};
  const zhuanfaSongs = (id) => {};
  const loadSongs = (id) => {};

  const { playLists } = useSelector(
    (state) => ({
      playLists: state.getIn(["player", "songLists"]),
    }),
    shallowEqual
  );

  useEffect(() => {
    if (playLists[0]) {
      setBtnNumber(playLists[0].id);
    }
  }, [playLists]);

  const close = () => {
    setOpen(false);
  };

  return (
    <SongListStyle>
      {createPortal(
        <CoverMask close={close} open={open} />,
        document.getElementById("root")
      )}
      <div className="songTableTitle">
        <span className="song-list">歌曲列表</span>
        <span className="song-number">{props.songLength}首歌</span>
        <div className="fr song-time-r">
          <span className="play-time">
            播放：<span className="play-time-number">{props.playCount}</span>次
          </span>
        </div>
      </div>
      <div className="playList-table">
        <table>
          <thead className="sprite_table">
            <tr>
              <th className="first-kb sprite_table"></th>
              <th className="bt sprite_table">
                <div className="wp sprite_table">标题</div>
              </th>
              <th className="sc sprite_table">
                <div className="wp sprite_table">时长</div>
              </th>
              <th className="gs sprite_table">
                <div className="wp sprite_table">歌手</div>
              </th>
            </tr>
          </thead>
          <tbody>
            {props.songLength === "" ? (
              <tr></tr>
            ) : (
              props.tracks.map((item, index) => {
                const playing = item.id === btnNumber;
                return (
                  <tr ref={trBoxRef} className="tr-box" key={item.id}>
                    <td className="tr-num">
                      <div className="tr-num-div">
                        <span>{index + 1}</span>
                        <i></i>
                      </div>
                    </td>
                    <td className="tr-name">
                      <div className="tr-div">
                        {index < 3 ? (
                          <img
                            className="fl"
                            src={getSizeImage(item.al.picUrl, 50)}
                            alt=""
                          />
                        ) : (
                          ""
                        )}
                        <div className="tr-div-box">
                          <i
                            onClick={(e) => getMusicLists(item.id)}
                            className={
                              index < 3
                                ? playing
                                  ? "playing tr-name-play-three fl"
                                  : "tr-name-play sprite_table tr-name-play-three fl"
                                : playing
                                ? "playing fl"
                                : "tr-name-play sprite_table fl"
                            }
                          ></i>
                          <div className="tr-div-text">
                            <span
                              className={
                                index < 3 ? "txt-max-three txt-max" : "txt-max"
                              }
                            >
                              <NavLink
                                to={{
                                  pathname: "/song",
                                  search: "?id=" + item.id,
                                }}
                                className={
                                  index < 3
                                    ? "tr-name-span tr-name-span-three"
                                    : "tr-name-span"
                                }
                              >
                                {item.name}
                              </NavLink>
                              {item.alia.length !== 0
                                ? item.alia.map((itemb, indexb) => {
                                    return (
                                      <span
                                        key={indexb + Math.random()}
                                        className={
                                          indexb < 3
                                            ? "tr-span-three"
                                            : "tr-span"
                                        }
                                      >
                                        -（{indexb === 0 ? itemb : "/" + itemb}
                                        ）
                                      </span>
                                    );
                                  })
                                : ""}
                              {item.mv !== 0 ? (
                                <NavLink
                                  to={{
                                    pathname: "/mv",
                                    search: "?id=" + item.mv,
                                  }}
                                >
                                  <i className="mv-icon tablepng"></i>
                                </NavLink>
                              ) : (
                                <React.Fragment></React.Fragment>
                              )}
                            </span>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="tr-time">
                      <div className="tr-time-times">
                        {formalMinuteSeconds(item.dt)}
                      </div>
                      <Four
                        id={item.id}
                        collectSongs={(e) => collectSongs(item.id)}
                        zhuanfaSongs={(e) => zhuanfaSongs(item.id)}
                        loadSongs={(e) => loadSongs(item.id)}
                      />
                    </td>
                    <td className="tr-songer">
                      <div>
                        <span>
                          {item.ar.map((itema, indexa) => {
                            return (
                              <NavLink
                                to={{
                                  pathname: "/artist",
                                  search: "?id=" + itema.id,
                                }}
                                key={itema.name}
                              >
                                {getfg(itema.name, item, indexa, itema.id)}
                              </NavLink>
                            );
                          })}
                        </span>
                      </div>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </SongListStyle>
  );
});
